import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import * as SecureStore from 'expo-secure-store';

interface GiftReward {
    id: string; // 唯一标识
    time: string; // 打赏时间
    diamonds: number; // 打赏的钻石数量
    giftName: string; // 礼物名称
}

interface GiftRewardState {
    giftRewards: GiftReward[]; // 打赏记录数组
}

const initialState: GiftRewardState = {
    giftRewards: [],
};

const giftRewardSlice = createSlice({
    name: 'giftReward',
    initialState,
    reducers: {
        addGiftReward(state, action: PayloadAction<GiftReward>) {
            state.giftRewards.push(action.payload); // 添加新的打赏记录
            console.log(state.giftRewards);
            // 同步保存到 SecureStore
            SecureStore.setItemAsync('giftRewards', JSON.stringify(state.giftRewards))
                .catch((error) => {
                    console.error('Error saving giftRewards to SecureStore:', error);
                });
        },
        clearGiftRewards(state) {
            state.giftRewards = [];
            // 清空 SecureStore 中的打赏记录
            SecureStore.setItemAsync('giftRewards', JSON.stringify(state.giftRewards))
                .catch((error) => {
                    console.error('Error clearing giftRewards in SecureStore:', error);
                });
        },
    },
});

export const { addGiftReward, clearGiftRewards } = giftRewardSlice.actions;
export default giftRewardSlice.reducer;
